package com.sfang.common.base.feign;

import com.sfang.common.base.constants.Constants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author k
 * @date 2019-11-26
 */
@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate template) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                template.header(Constants.TRACK_ID, MDC.get(Constants.TRACK_ID));
            }
        } catch (IllegalArgumentException e) {
            log.error("error FeignConfiguration.apply", e);
        }
    }
}
